package com.example.concurrency.chapter10;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierTest {
    private static final int workerNum = 5;
    private static CyclicBarrier barrier = new CyclicBarrier(workerNum);

    public static void main(String[] args) {
        for (int i = 0; i < workerNum; i++){
            new Thread(new Task()).start();
        }
    }

    static class Task implements Runnable{
        @Override
        public void run() {
            try {
                String name = Thread.currentThread().getName();
                Thread.sleep(new Random().nextInt(5) * 1000);
                System.out.println("线程【" + name + "】达到");
                barrier.await();
                System.out.println("线程【" + name + "】执行");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }

        }
    }
}
